﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace be.metanous.mvvm.utils
{
    public class InstanceDataTemplateSelector : DataTemplateSelector, IDisposable
    {
        private Dictionary<object, DataTemplate> _dataTemplates = new Dictionary<object, DataTemplate>();

        public Dictionary<object, DataTemplate> DataTemplates { get { return _dataTemplates; } }

        public InstanceDataTemplateSelector()
        {
            
        }

        public InstanceDataTemplateSelector(object item, DataTemplate dataTemplate)
        {
            Add(item, dataTemplate);
            
        }

        public void Add(object item, DataTemplate dataTemplate)
        {
            if (item != null && dataTemplate != null)
            {
                _dataTemplates.Add(item, dataTemplate);
            }
        }

        public void Clear()
        {
            _dataTemplates.Clear();
        }


        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
          
            if (item != null && DataTemplates.ContainsKey(item))
            {
                var dataTemplate = DataTemplates[item];
                if (dataTemplate != null)
                {
                    return dataTemplate;
                }
            }
            return base.SelectTemplate(item, container);
        }

        public void Dispose()
        {
            _dataTemplates.Clear();
        }
    }
}
